<template>
  <el-dialog model-value="dialogVisible" :title="dialogTitle" width="60%" @close="handleClose">
    <div style="max-height: 520px;overflow: auto;">
      <el-form :inline="true" ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="样地位置" prop="address">
          <!-- <el-input v-model="form.address" /> -->
          <el-cascader v-model="form.address" :options="addressList" :props="props_cascader" clearable
            placeholder="请选择" />
          <!-- <br><span style="color: grey;font-size: 12px; padding-left: 5px;">如样地不存在，请先在[样地管理]模块添加！</span> -->
        </el-form-item>
        <el-form-item label="造林年度" prop="year" style="width: 250px;">
          <el-date-picker v-model="form.year" type="year" placeholder="选择年份" />
        </el-form-item>
        <el-form-item label="树种" prop="treeSpecies" style="width: 250px;">
          <el-cascader v-model="form.treeSpecies" :options="treeSpeciesList" clearable placeholder="请选择" />
        </el-form-item>
        <el-form-item label="样木编号" prop="number">
          <el-input-number v-model="form.number" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="坐标X" prop="X">
          <el-input-number v-model="form.X" :min="0" :precision="8" :step="0.01" controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="坐标Y" prop="Y">
          <el-input-number v-model="form.Y" :min="0" :precision="8" :step="0.01" controls-position="right">
          </el-input-number>
        </el-form-item>
        <br>
        <el-form-item label="树高" prop="TH">
          <el-input-number v-model="form.TH" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>m</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="胸径" prop="DBH">
          <el-input-number v-model="form.DBH" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>cm</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="径阶" prop="DC">
          <el-input-number v-model="form.DC" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>cm</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="材积" prop="volume">
          <el-input-number v-model="form.volume" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>m³</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="枝下高" prop="HFLB">
          <el-input-number v-model="form.HFLB" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>m</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="南北" prop="CW_SN">
          <el-input-number v-model="form.CW_SN" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>m</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="东西" prop="CW_EW">
          <el-input-number v-model="form.CW_EW" :min="0" :precision="1" :step="0.1" controls-position="right">
            <template #suffix> <span>m</span> </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 250px;">
          <el-input v-model="form.remark" type="textarea" :rows="1" />
        </el-form-item>

      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import api, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus'

let addressList = []
let treeSpeciesList = []

// 设置hover触发子菜单
const props_cascader = {
  expandTrigger: 'hover',
}
// 初始化字段列表
const initField = async () => {
  await api.get("treeSpecies/list").then((res) => {
    for (let item of res.data.data) {
      if (item.status) {
        treeSpeciesList.push({ value: item.id, label: item.name })
      }
    }
  })
  await api.get("address/list").then((res) => {
    for (let item of res.data.data) {
      addressList = res.data.select_data
    }
  })
}

const props = defineProps(
  {
    id: {
      type: Number,
      default: -1,
      required: true
    },
    dialogTitle: {
      type: String,
      default: '',
      required: true
    },
    dialogVisible: {
      type: Boolean,
      default: false,
      required: true
    }
  }
)

const form = ref({
  id: -1,
  address: 0,
  year: new Date(),
  treeSpecies: 0,
  number: 0,
  X: 0,
  Y: 0,
  TH: 0,
  DBH: 0,
  DC: 0,
  volume: 0,
  HFLB: 0,
  CW_SN: 0,
  CW_EW: 0,
  remark: '',
})


const rules = ref({
  address: [
    { required: true, message: '请选择样地！' },
  ],
  treeSpecies: [
    { required: true, message: '请选择树种！' },
  ],
  year: [
    {
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback(new Error(`请选择年份`)) // 允许为空
          return
        }

        const currentYear = new Date().getFullYear()
        if (value.getFullYear() > currentYear) {
          callback(new Error(`年份不能大于当前年份: ${currentYear}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  number: [
    { required: true, message: '请输入样木编号！' },
    { type: 'integer', message: '样木编号须为整数!', trigger: 'blur' }
  ],
  TH: [
    { type: 'number', message: '必须为数字', trigger: 'blur' },
  ]
})

const formRef = ref(null)

const initFormData = async (id) => {
  const res = await api.get("tree/action?id=" + id);
  form.value = res.data.data;
  form.value.year = new Date(res.data.data.year, 0, 1);  // 将年份数字转为日期格式
}


watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id != -1) {
      initFormData(id)
    } else {
      form.value = {
        id: -1,
        address: 0,
        year: new Date(),
        treeSpecies: 0,
        number: null,
        X: null,
        Y: null,
        TH: null,
        DBH: null,
        DC: null,
        volume: null,
        HFLB: null,
        CW_SN: null,
        CW_EW: null,
        remark: '',
      }
    }

  }
)


const emits = defineEmits(['update:modelValue', 'initTreeList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log('@@', form.value.address, form.value.treeSpecies)
      form.value.year = form.value.year.getFullYear()

      if (Array.isArray(form.value.address)) {
        form.value.address = form.value.address[0];
      }
      if (Array.isArray(form.value.treeSpecies)) {
        form.value.treeSpecies = form.value.treeSpecies[0];
      }
      // form.value.treeSpecies = form.value.treeSpecies[0]
      // form.value.address = form.value.address[0]
      let result = await api.post("tree/save", form.value);
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success(data.msg)
        formRef.value.resetFields();
        emits("initTreeList")
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("字段校验失败！")
    }
  })
}

initField()
</script>

<style scoped></style>
